package org.infosec.lc.exercises.apacheBeanUtils;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;

/**
	文件名：ApacheBeanUtils.java
	作  者：林超
	时  间：2011-5-11下午04:21:18

	功能描述：Test Apache and Spring BeanUtils.copyProperties()
	
	pom.xml	:
			
 */
public class ApacheBeanUtils {

	/**	测试结果
	 * 		Apache：BeanUtils.copyProperties("目标Entity","源Entity")
	 * 			1、源Entity中Integer --> 目标Entity中String     （可成功）
	 * 			2、源Entity中String --> 目标Entity中Integer	   （可成功，但 源Entity中String不为numeral型，赋为"0"）
	 * 			3、源Entity中null --> 目标Entity中Integer     （可成功,值为"0"）
	 * 
	 * 		Spring：BeanUtils.copyProperties("源Entity","目标Entity")
	 * 			1、源Entity中Integer --> 目标Entity中String     （不成功）
	 * 			2、源Entity中String --> 目标Entity中Integer	   （不成功）
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		
		//现在正测试
		int test = 1;
		
		if(test==1){
			/**
			 * 测试一：BeanUtils.copyProperties("目标Entity","源Entity")
			 */
			Test1();
		}else if(test==2){
			/**
			 * 测试二： Class newInstance = clazz.newInstance();
					   BeanUtils.copyProperty(newInstance, "对象属性", srcString.toString());
			 */
			Test2();
		}
	}

	@SuppressWarnings("unchecked")
	private static void Test2() {
		Class clazz = TestBean1.class;
		Object newInstance = null;
		String srcString = "XXX";
		System.out.println(clazz.getSimpleName());
		try {
			newInstance = clazz.newInstance();
			BeanUtils.copyProperty(newInstance, "name", srcString.toString());	//注：此处要有*.toString()
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		System.out.println(newInstance);
		System.out.println(((TestBean1)newInstance).getName());
	}

	private static void Test1() {
		TestBean1 bean1 = new TestBean1("aaa",3);
		TestBean2 bean2 = new TestBean2("BBB",null);
		
		try {
			BeanUtils.copyProperties(bean1, bean2);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		System.out.println(bean1.name + "\n" + bean1.age);
		System.out.println(bean2.name + "\n" + bean2.age);
	}

}

